import React, { useState, useEffect } from 'react';
import { LoginForm } from './components/LoginForm';
import { MainLayout } from './components/MainLayout';

export type UserRole = 'student' | 'teacher' | 'admin';

export interface User {
  id: string;
  name: string;
  role: UserRole;
  email: string;
  avatar?: string;
  studentId?: string;
  teacherId?: string;
}

export default function App() {
  const [user, setUser] = useState<User | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    // Check for existing session
    const savedUser = localStorage.getItem('currentUser');
    if (savedUser) {
      setUser(JSON.parse(savedUser));
    }
    setIsLoading(false);
  }, []);

  const handleLogin = (loginData: { username: string; password: string; role: UserRole }) => {
    // Mock login logic - in real app, this would call an API
    const mockUser: User = {
      id: `${loginData.role}_001`,
      name: loginData.role === 'student' ? '张三' : 
            loginData.role === 'teacher' ? '李老师' : '王管理员',
      role: loginData.role,
      email: `${loginData.username}@university.edu.cn`,
      ...(loginData.role === 'student' && { studentId: '2024001001' }),
      ...(loginData.role === 'teacher' && { teacherId: 'T2024001' })
    };
    
    setUser(mockUser);
    localStorage.setItem('currentUser', JSON.stringify(mockUser));
  };

  const handleLogout = () => {
    setUser(null);
    localStorage.removeItem('currentUser');
  };

  if (isLoading) {
    return (
      <div className="size-full flex items-center justify-center">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
      </div>
    );
  }

  if (!user) {
    return <LoginForm onLogin={handleLogin} />;
  }

  return <MainLayout user={user} onLogout={handleLogout} />;
}